package com.xiaolin.thirtpart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName LoginController
 * @Description 第三方登录-以微博登录为例
 * @Detail    测试登录
 * @Author MyPC
 * @Date 2020/10/7
 * @Version 1.0
 */
@Controller
//@RequestMapping("/auth")
public class TestLoginController {
    @Autowired
    private RestTemplate restTemplate;
    @Value("${third.appkey}")
    private String appKey;
    @Value("${third.AppSecret}")
    private String appSecret;
    @Value("${third.redirectUri}")
    private String redirectUri;

    /**
     * 获取授权码、token和用户信息
     *  注：使用这种方式无法获取到token
     * @param code
     * @return
     */
    @RequestMapping("/access")
    public String loginAccess(@RequestParam("code") String code) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        sb.append("https://api.weibo.com")
                .append("/oauth2/access_token?")
                .append("client_id=").append(appKey).append("&")
                .append("client_secret=").append(appSecret).append("&")
                .append("scope=all&")
                .append("grant_type=authorization_code&")
                .append(URLEncoder.encode(redirectUri, "UTF-8"));
        String accessTokenRequestPath = sb.toString();
        Map<String,String> map=new HashMap<>();
        map.put("code",code);
        map.put("redirect_uri",redirectUri);
        RestTemplate request=new RestTemplate();
        accessTokenRequestPath+="&code="+code;
        String s=request.postForObject(accessTokenRequestPath,String.class, String.class,map);
        System.out.println("accessTokenUrl返回的数据:"+sb);
        JSONObject  body= JSONObject.parseObject(s);
        String access_token = body.getString("access_token");
        String uid = body.getString("uid");
        //获取用户信息
        Map userInfo = restTemplate.getForObject("https://api.weibo.com/2/users/show.json?access_token="+access_token+"&uid="+uid, Map.class);
        System.out.println(userInfo);
        return "index";
    }
}
